package com.michael.demos.base.proxy.dynamic.jdk;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * 类功能描述:
 * <pre>
 *   JDK动态代理 - 代理(中介)
 * </pre>
 *
 * @author Michael
 * @version 1.0
 * @date 2020/8/4 10:02
 */
public class ServiceHandler implements InvocationHandler {

    private IService realService;

    public ServiceHandler(IService realService) {
        this.realService = realService;
    }

    public ServiceHandler() {
        this.realService = new RealService();
    }

    /** 代理增强 - 代理方法执行前后 */
    private void around() {
        System.out.println("[Proxy]:around ……");
    }

    /** 代理增强 - 代理方法执行前 */
    private void before() {
        System.out.println("[Proxy]:before ……");
    }

    /** 代理增强 - 代理方法执行后 */
    private void after() {
        System.out.println("[Proxy]:after ……");
    }

    /** 代理增强 - 代理方法执行异常后 */
    private void afterThrowing(Exception e) {
        //e.printStackTrace();
        System.out.println("[Proxy]: ！！！afterThrowing ……");
    }

    /** 代理增强 - 代理方法正常执行完成后 */
    private void afterReturning() {
        System.out.println("[Proxy]:afterReturning ……");
    }

    /** 模拟 Spring AOP增强逻辑 */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        around();
        before();

        Exception ex = null;

        try {
            method.invoke(realService, args);
        } catch (Exception e) {
            ex = e;
        }
        around();
        if (ex == null) {
            after();
            afterReturning();
        } else {
            after();
            afterThrowing(ex);
        }
        return null;
    }
}

